#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：back 
@File    ：Identity_token_dao.py
@IDE     ：PyCharm 
@Author  ：七分是你
@Date    ：2024/6/29 下午7:32 
@explain : 
"""

from app.dao.models import XlxIdentityToken
from . import tools
from .base_dao import getDatabaseSession


class IdentityTokenQueryDao:
    @classmethod
    def find(cls, **kwargs) -> XlxIdentityToken:
        with getDatabaseSession() as session:
            query = session.query(XlxIdentityToken)
            query = tools.build_query(query, XlxIdentityToken, **kwargs)
            result = query.one_or_none()
        return result


class IdentityTokenOperateDao(object):
    @classmethod
    def delete_token(cls, mdtoken: str):
        with getDatabaseSession() as session:
            token = session.query(XlxIdentityToken).filter_by(mdtoken=mdtoken).first()
            if token:
                session.delete(token)

    @classmethod
    def save(cls, data: dict) -> XlxIdentityToken:
        with getDatabaseSession() as session:
            existing_token = session.query(XlxIdentityToken).filter_by(uid=data['uid']).first()
            if existing_token:
                existing_token.mdtoken = data['mdtoken']
                existing_token.expire = data['expire']
                existing_token.uid = data['uid']
                existing_token.updatetime = data['updatetime']
            else:
                new_token = XlxIdentityToken(mdtoken=data['mdtoken'], expire=data['expire'],
                                             updatetime=data['updatetime'])
                session.add(new_token)
            session.flush()
            session.commit()
        return existing_token or new_token
